import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
import datetime

class DormitoryCreator:
    def __init__(self):
        self.db = Database()
    
    def create_dormitory(self, building, room_number, capacity):
        """
        创建新宿舍
        
        参数:
            building (str): 宿舍楼号
            room_number (str): 房间号
            capacity (int): 容纳人数
        
        返回:
            bool: 创建成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not building or not room_number or not capacity:
                print("错误：所有字段都必须填写")
                return False
            
            try:
                capacity = int(capacity)
                if capacity <= 0:
                    print("错误：容量必须是正整数")
                    return False
            except ValueError:
                print("错误：容量必须是数字")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查是否已存在相同宿舍
            self.db.cursor.execute(
                "SELECT id FROM dormitory WHERE building = ? AND room_number = ?",
                (building, room_number)
            )
            if self.db.cursor.fetchone():
                print(f"错误：宿舍 {building}-{room_number} 已存在")
                self.db.close()
                return False
            
            # 插入新宿舍
            self.db.cursor.execute(
                "INSERT INTO dormitory (building, room_number, capacity) VALUES (?, ?, ?)",
                (building, room_number, capacity)
            )
            self.db.conn.commit()
            print(f"成功：宿舍 {building}-{room_number} 创建成功，可容纳 {capacity} 人")
            return True
        except Exception as e:
            print(f"错误：创建宿舍时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def batch_create_dormitories(self, dormitories_data):
        """
        批量创建宿舍
        
        参数:
            dormitories_data (list): 宿舍信息列表，每个元素是包含宿舍信息的元组
                                  (building, room_number, capacity)
        
        返回:
            tuple: (成功创建数量, 总数量)
        """
        success_count = 0
        total_count = len(dormitories_data)
        
        try:
            self.db.connect()
            
            for dormitory_data in dormitories_data:
                building, room_number, capacity = dormitory_data
                
                # 验证输入
                if not building or not room_number or not capacity:
                    print(f"错误：宿舍 {building}-{room_number} 的信息不完整，跳过")
                    continue
                
                try:
                    capacity = int(capacity)
                    if capacity <= 0:
                        print(f"错误：宿舍 {building}-{room_number} 的容量必须是正整数，跳过")
                        continue
                except ValueError:
                    print(f"错误：宿舍 {building}-{room_number} 的容量必须是数字，跳过")
                    continue
                
                # 检查是否已存在相同宿舍
                self.db.cursor.execute(
                    "SELECT id FROM dormitory WHERE building = ? AND room_number = ?",
                    (building, room_number)
                )
                if self.db.cursor.fetchone():
                    print(f"错误：宿舍 {building}-{room_number} 已存在，跳过")
                    continue
                
                # 插入新宿舍
                try:
                    self.db.cursor.execute(
                        "INSERT INTO dormitory (building, room_number, capacity) VALUES (?, ?, ?)",
                        (building, room_number, capacity)
                    )
                    self.db.conn.commit()
                    success_count += 1
                    print(f"成功：宿舍 {building}-{room_number} 创建成功，可容纳 {capacity} 人")
                except Exception as e:
                    print(f"错误：创建宿舍 {building}-{room_number} 时发生错误 - {str(e)}")
                    self.db.conn.rollback()
            
            return success_count, total_count
        except Exception as e:
            print(f"错误：批量创建宿舍时发生错误 - {str(e)}")
            return success_count, total_count
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    creator = DormitoryCreator()
    
    print("===== 宿舍创建 =====")
    building = input("请输入宿舍楼号: ")
    room_number = input("请输入房间号: ")
    capacity = input("请输入容纳人数: ")
    
    creator.create_dormitory(building, room_number, capacity)